package com.cy.pet.item.aspect;

import com.cy.pet.common.pojo.BrowerLog;
import com.cy.pet.common.pojo.Item;
import com.cy.pet.common.service.BrowerLogService;
import com.cy.pet.common.vo.SysResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/10/8 10:06
 */
@Slf4j
@Aspect //声明此类为切面类
@Component //交给spring管理
public class LogAspect {
    @Autowired
    private BrowerLogService browerLogService;

    @Pointcut("@annotation(com.cy.pet.item.annotation.BrowseLog)")
    public void doLog(){}

    @Around("doLog()") //此注解描述的方法内部可以调用执行链
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.debug("Before{}",System.currentTimeMillis());
        Object result = joinPoint.proceed(); //执行链
        log.debug("After{}",System.currentTimeMillis());
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("principal="+principal);
        System.out.println(result);
        //从result中获取item对象
        SysResult result1 = (SysResult)result;
        Item item = (Item)result1.getData();
        //根据商品信息，构建浏览记录对象
        BrowerLog browerLog = new BrowerLog();
        browerLog.setItemId(item.getId())
                .setPrice(item.getPrice())
                .setTitle(item.getTitle());
        //将浏览记录存到数据库中
        browerLogService.setLog(browerLog);
        return result;
    }
}
